<template>
  <div>
    <el-button
      type="primary"
      size="default"
      icon="el-icon-plus"
      style="margin-bottom: 10px"
      @click="dialogFormVisible = true"
      >添加用户</el-button
    >
    <el-table :data="userList" border stripe>
      <el-table-column label="序号" width="80px" align="center">
        <template v-slot="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名"> </el-table-column>
      <el-table-column prop="name" label="角色"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            @click="editData(row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="deleteItem(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="uForm._id ? '修改用户' : '添加用户'"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        :model="uForm"
        ref="userForms"
        style="width: 80%"
        :rules="userRules"
      >
        <el-form-item label="用户名" label-width="100px" prop="username">
          <el-input v-model="uForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" label-width="100px" prop="role">
          <el-select v-model="uForm.role" placeholder="请选择角色">
            <el-option
              v-for="item in roleList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="uForm._id ? '修改密码' : '' + '密码'"
          label-width="100px"
          prop="password"
        >
          <el-input
            placeholder="请输入密码"
            v-model="uForm.password"
            show-password
          />
        </el-form-item>
        <el-form-item
          :label="uForm._id ? '确认修改密码' : '' + '确认密码'"
          label-width="100px"
          prop="repassword"
        >
          <el-input
            placeholder="请再次输入密码"
            v-model="uForm.repassword"
            show-password
          />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="cancelDialog">取消</el-button>
        <el-button type="primary" @click="submitData">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    // 自定义校验规则
    // 密码
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.uForm.repassword !== "") {
          this.$refs.userForms.validateField("repassword");
        }
        callback();
      }
    };
    // 确认密码
    let validateRePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.uForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      userList: [],
      roleList: [],
      uForm: {},
      dialogFormVisible: false,
      // 表单校验规则
      userRules: {
        password: [
          {
            validator: validatePass,
            trigger: "blur",
          },
          {
            min: 6,
            message: "长度不能小于6",
            trigger: "blur",
          },
        ],
        repassword: [
          { validator: validateRePass, trigger: "blur" },
          {
            min: 6,
            message: "长度不能小于6",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.getAllUser();
    this.getRole();
  },
  methods: {
    async getAllUser() {
      let ret = await reqAllUser();
      if (ret.code == 200)
        this.userList = ret.data.map((item) => ({
          ...item,
          name: item.role?.name,
          role: item.role?._id,
        }));
    },
    async getRole() {
      let ret = await reqRole();
      if (ret.code == 200) this.roleList = ret.data;
    },
    // 点击取消按钮
    cancelDialog() {
      this.uForm.username = "";
      this.uForm.password = undefined;
      this.uForm.repassword = undefined;
      this.uForm.role = undefined;
      this.uForm._id = undefined;
      this.dialogFormVisible = false;
    },
    // 点击叉号关闭
    handleClose(done) {
      this.$confirm("确认关闭？", "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((_) => {
          this.cancelDialog();
          done();
        })
        .catch((_) => {});
    },
    editData(item) {
      this.dialogFormVisible = true;
      this.uForm = {
        _id: item._id,
        username: item.username,
        role: item.role,
      };
    },
    deleteItem(row) {
      this.$confirm(`你确定删除${row.username}?`, "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //当用户点击确定按钮的时候会出发
          //向服务器发请求
          let result = await reqDeleteUser({ id: row._id });
          //如果删除成功
          if (result.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //再次获取种类列表数据
            this.getAllUser();
          }
        })
        .catch(() => {
          //当用户点击取消按钮的时候会触发
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async submitData() {
      this.$refs.userForms.validate(async (valid) => {
        if (valid) {
          delete this.uForm.repassword;
          if (!this.uForm.password?.trim()) delete this.uForm.password;
          let ret = await reqAddOrUpdateUser(this.uForm);
          let tip = this.uForm._id ? "用户修改成功" : "用户添加成功";
          if (ret.code == 200) {
            this.$message.success(tip);
            this.cancelDialog();
            this.getAllUser();
          }
        } else {
          return this.$message.error("请按照要求正确输入！");
        }
      });
    },
  },
};
</script>

<style></style>
